import { Controller } from 'egg';
import * as dayjs from 'dayjs';
export default class extends Controller {
  /**
   * @description: 保存草稿
   * @param {type}
   * @return:
   */
  async saveDraft() {
    const { ctx, service } = this;
    const { content, id, articleId } = ctx.request.body;
    const authorId = ctx.userId;
    if (!content) {
      return ctx.body = '';
    }
    if (id) {
      await service.draft.doUpdate(id, {
        content,
        authorId,
        articleId,
      });
      ctx.ok({
        id,
        hasDraft: true,
        time: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
      }, '保存成功');
    } else {
      const draft = await service.draft.doSave({
        authorId,
        articleId,
        content,
        status: 1,
      });
      ctx.ok({
        id: draft.id,
        hasDraft: true,
        time: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
      }, '保存成功');
    }
  }
  /*
  * 获取用户的草稿
  * 需要登陆
  */
  async getMeDrafts() {
    const { ctx, service } = this;
    const authorId = ctx.userId;
    const drafts = await service.draft.getDrafts(authorId);
    const hasDraft = drafts.length > 0 ? true : false;
    ctx.ok({
      drafts,
      hasDraft,
    });
  }
}
